package io.geekidea.boot.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.geekidea.boot.framework.exception.BusinessException;
import io.geekidea.boot.system.dto.ResourceTypeDto;
import io.geekidea.boot.system.entity.ResourceType;
import io.geekidea.boot.system.entity.SysDictType;
import io.geekidea.boot.system.mapper.ResourceTypeMapper;
import io.geekidea.boot.system.query.ResourceTypeQuery;
import io.geekidea.boot.system.service.ResourceTypeService;
import io.geekidea.boot.system.vo.ResourceTypeVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 资源类型 服务实现类
 */
@Service
public class ResourceTypeServiceImpl extends ServiceImpl<ResourceTypeMapper, ResourceType>
        implements ResourceTypeService {

    @Autowired
    private ResourceTypeMapper resourceTypeMapper;

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean addResourceType(ResourceTypeDto dto) {
        checkCodeExists(dto.getCode());
        ResourceType resourceType = new ResourceType();
        BeanUtils.copyProperties(dto, resourceType);
        return save(resourceType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateResourceType(ResourceTypeDto dto) {
        ResourceType resourceType = getById(dto.getId());
        if (resourceType == null) {
            throw new RuntimeException("资源类型不存在");
        }
        BeanUtils.copyProperties(dto, resourceType);
        return updateById(resourceType);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteResourceType(Long id) {
        return removeById(id);
    }

    @Override
    public ResourceTypeVo getResourceTypeById(Long id) {
        return resourceTypeMapper.getResourceTypeById(id);
    }

    @Override
    public List<ResourceTypeVo> getResourceTypeList(ResourceTypeQuery query) {
        return resourceTypeMapper.getResourceTypeList(query);
    }

    @Override
    public void checkCodeExists(String code) {
        LambdaQueryWrapper<ResourceType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ResourceType::getCode, code);
        long count = count(wrapper);
        if (count > 0) {
            throw new BusinessException(code + "类型编码已经存在");
        }
    }
}
